<?php defined('BASEPATH') || exit('No direct script access allowed');

/**
 * Building controller
 */
class Area extends REST_Controller
{
    function __construct()
    {
        // Construct the parent class
        parent::__construct();
    }


    public function index_post()
    {
        $flag = false;
        $post = $this->post();
        $this->validPost($post);
        $this->load->model('area/area_model');
        $areaField = ['parent_id'=>'父级ID', 'area_name'=>'区域名称', 'area_type'=>'区域类型'];
        $data = [];
        foreach ($areaField as $key=>$val) {
            if (isset($post[$key])) {
                $data[$key] = $post[$key];
            }
        }
        // 写入区域表
        $id = $this->area_model->insert($data);
        if (is_numeric($id)) $flag = true;
        $flag ? $this->response(['status'=>true, 'data'=>$post], REST_Controller::HTTP_CREATED) : $this->response(['status'=>false, 'message'=>'数据写入失败'], REST_Controller::HTTP_INTERNAL_SERVER_ERROR);
    }

    public function index_patch($id)
    {
        //接受参数
        $patch = $this->patch();
        $this->load->model('vendor/area_model');
        $areaOne = $this->area_model->find_by(['area_id'=>$id]);
        if(empty($id) || !$areaOne) $this->response(['status'=>false, 'message'=>'请求参数错误'], REST_Controller::HTTP_INTERNAL_SERVER_ERROR);
        $res = !empty($patch) ? $this->vendor_model->update(['area_id'=>$id], $patch) : 0;
        if($res){
            $this->response(['status'=>true, 'data'=>"区域更新成功"], REST_Controller::HTTP_CREATED);
        }else{
            $this->response(['status'=>false, 'message'=>'区域更新失败'], REST_Controller::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    public function index_get()
    {
        $post = $this->get();
        $this->response($post);
    }

    private function validPost($data)
    {
        $require = ['parent_id'=>'父级ID', 'area_name'=>'区域名称', 'area_type'=>'区域类型'];
        foreach ($require as $key => $val) {
            if (!isset($data[$key]) || empty($data[$key])) {
                $this->response(['status'=>false, 'message'=>$val.' 不能为空'], REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
                break;
            }
        }
    }
}